package com.bang.study.day06;

/**
 * @Auther: Bang
 * @Date: 2019/9/17 0017 16:48
 * @Description:
 */
public class UnionFind1 implements UF {

    private int[] id;

    public UnionFind1(int size) {
        this.id = new int[size];
        for (int i = 0; i <size ; i++) {
            id[i] = i;
        }

    }

    @Override
    public int getSize() {
        return id.length;
    }

    /**
     * 查找元素p所对应的集合编号
     * @param p
     * @return
     */
    private int find(int p){
        if(p < 0 || p >= id.length) {
            throw new IllegalArgumentException("p is out of bound.");
        }
        return id[p];
    }

    /**
     * p和q是否同属于一个集合
     *
     * @param p
     * @param q
     * @return
     */
    @Override
    public boolean isConnected(int p, int q) {
        return find(p)==find(q);
    }

    /**
     * 连接p和q
     *
     * @param p
     * @param q
     */
    @Override
    public void unionElements(int p, int q) {
        int pId = find(p);
        int qId = find(q);
        if (pId==qId){
            return;
        }
        // 合并操作
        for (int i = 0; i < id.length; i++) {
            if (id[i]==pId) {
                id[i] = qId;
            }
        }
    }
}
